package com.changgou.consumer.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.consumer.config.RabbitMqConfig;
import com.changgou.consumer.service.SeckillOrderService;
import com.changgou.seckill.pojo.SeckillOrder;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 戴金华
 * @date 2019-12-30 21:18
 */
@Component
public class ConsumeListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    @RabbitListener(queues = RabbitMqConfig.SECKILL_ORDER_KEY)
    public void receiveSeckillOrderMessage(Channel channel, Message message){
        //转换消息
        SeckillOrder seckillOrder = JSON.parseObject(message.getBody(), SeckillOrder.class);

        //同步mysql的订单
        int rows = seckillOrderService.createOrder(seckillOrder);
        if (rows>0){
            //创建成功 返回成功通知
            try {
                /**
                 * 1 消息的唯一标识
                 * 2 是否开启批处理
                 */
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            //同步mysql失败
            try {
                /**
                 * 1 消息的唯一标识
                 * 2 true 所有消费者都会拒绝这个消息 false只有当前消费者拒绝
                 * 3 true 当前消息会进入到死信队列   false重新回到原有队列中
                 */
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
